<template>
  <div>
    <div  style="height:205px;background: #fff;padding-right: 10px;">
      <split-vertical :title="title"></split-vertical>
      <v-form :formProps="editForm" ref="form"
              v-on:selectOnChange="selectOnChange"
              v-on:handleReset="handleReset"
              v-on:elseBtnHandleReset="elseBtnHandleReset"
              v-on:coverFormData="coverFormData"></v-form>
    </div>
    <div class="stand">
      <div style="line-height:45px;margin:0 10px">
    <el-row>
      <el-col :span="4">
        <el-button type="primary" @click="emptySelectProduct" size="small">清空采购内容</el-button>
      </el-col>
      <el-col :span="20">
        <div style="float: right">
          <span class="tip-purchase"> 总采购价:&nbsp;<span class="tip-purchase-price">￥{{totalArray[0]}}</span></span>
          <span class="tip-purchase"> 总数量:&nbsp;<span class="tip-purchase-price">{{totalArray[1]}}/个</span></span>
          <span class="tip-purchase"> 总额外费用:&nbsp;<span class="tip-purchase-price">￥{{totalArray[2]}}</span></span>
        </div>
      </el-col>
    </el-row>
    </div>

    <v-table :tableParams="tableParams"
             v-on:inputNumChange="inputNumChange"
             v-on:handleOperation="handleOperation"
             style="margin-top: 10px"></v-table>

    </div>
  </div>
</template>
<script>
  import VTable from "components/common/PageTable/VTable"
  import VForm from "components/common/VForm"
  import VButton from "components/common/VButton"
  import SplitVertical from "components/common/SplitVertical"
  import {localStorage} from 'js/localStorage'

  export default {
    components: {
      VForm, VTable, VButton, SplitVertical
    },
    data() {
      return {
        title: '新增采购计划',
        editForm: {
          col: 4,
          labelWidth: '120px',
          elseBtn: {
            show: true,
            text: '返回',
            type: 'default',
            size: 'small',
            style: {},
          },
          formItemArray: [{
            label: '订单类型',
            placeholder: "请选择",
            rules: [{required: true, message: '请选择订单类型', trigger: 'blur'}],
            prop: 'purOrderType',
            itemType: 'select',
            options: [
              {value: 1, label: '常规订单'},
              {value: 2, label: '集采订单'},
              {value: 3, label: '天猫订单'}
            ],
            value: ''
          }, {
            label: '单据日期',
            prop: 'purBillsDate',
            rules: [{required: true, message: '请选择单据日期', trigger: 'change'},],
            placeholder: "选择日期时间",
            itemType: 'dateTime',
            value: ''
          }, {
            label: '预计到货日期',
            prop: 'predictTime',
            placeholder: "选择日期时间",
            itemType: 'dateTime',
            rules: [{required: true, message: '请选择到货日期', trigger: 'change'},],
            value: ''
          }, {
            label: '采购公司',
            placeholder: "请选择",
            rules: [{required: true, message: '请选择采购公司', trigger: 'change'}],
            prop: 'companyId',
            itemType: 'select',
            options: [],
            value: ''
          }, {
            label: '选择仓库',
            placeholder: "请选择",
            prop: 'depotId',
            rules: [{required: true, message: '请选择仓库', trigger: 'change'},],
            itemType: 'select',
            options: [],
            value: ''
          }, {
            label: '供应商',
            placeholder: "请选择",
            prop: 'supplyId',
            rules: [{required: true, message: '请选择供应商', trigger: 'change'},],
            itemType: 'select',
            options: [],
            value: ''
          }, {
            label: '商品名称',
            placeholder: "请选择",
            prop: 'productId',
            // rules: [{required: true, message: '请选择商品名称', trigger: 'change'},],
            itemType: 'select',
            options: [],
            value: ''
          }]
        }, tableParams: {
          dataArray: [],
          showMultiSelection: false,
          showOperationColumn: true,
          operationColumnWidth: 100,
          columnArray: [
            {label: '商品名称', prop: 'productName', sortable: false, width: "240", formatType: 'a'},
            {label: '商品品牌', prop: 'brandCode', sortable: false, width: "100"},
            {label: '商品编码', prop: 'productNo', sortable: false, width: "100"},
            {label: '重量', prop: 'productWeight', sortable: false, width: '80',},
            {label: '进货价(含税运)', prop: 'purchasePrice', sortable: false, width: "120"},
            {
              label: '采购单价',
              prop: 'productPrice',
              sortable: false,
              width: "120",
              formatType: 'inputNum',
              step: 0.1,
              max: 999999999999,
              min: 0,
              unShowTip: true
            },
            {
              label: '采购数量',
              prop: 'purNumber',
              sortable: false,
              width: "120",
              formatType: 'inputNum',
              step: 0.1,
              max: 999999999999,
              min: 0,
              unShowTip: true
            },
            {label: '采购金额', prop: 'money', sortable: false, width: "110"},
            {
              label: '其他费用',
              prop: 'elsePrice',
              sortable: false,
              width: "120",
              formatType: 'inputNum',
              step: 0.1,
              max: 999999999999,
              min: 0,
              unShowTip: true
            },
            {label: '备注', prop: 'memo', sortable: false, formatType: 'input', unShowTip: true},
          ],
          rowHandle: {
            deleted: {
              text: '移除',
            },
            update: {
              show: false
            },
            view: {
              show: false
            },
          }
        },
        query: '',
        userId: '',
        dataCount: [0, 0, 0],
        totalArray: [0, 0, 0],
      }
    },
    created() {
      this.getSupplyList();
      //获取仓库
      this.getDepotData();
      //调用公司
      this.callCompany();
      this.userId = localStorage.get('userID');
      this.query = this.$route.query;
      if (this.query.action !== 'add') {
        this.title = '编辑采购计划';
        this.getItems();
      }
    },
    methods: {
      elseBtnHandleReset() {
        let query = {};
        if (this.query.action !== 'add') {
          query = {searchCondition: this.query.searchCondition}
        }
        this.$router.push({
          path: '/purchase-plan',
          query: query
        });
      },
      getItems() {
        let success = data => {
          if (data.code === 'OK') {
            this.tableParams.dataArray = data.data.items;
            this.editForm.formItemArray.forEach(item => {
              for (let key in data.data.entity) {
                if (item.prop === key) {
                  item.value = data.data.entity[key];
                  if (item.prop === 'supplyId') {
                    this.bySupplyGetShop(data.data.entity[key]);
                  }
                }
              }
            });

          } else {
            this.$message.error(data.msg);
          }
        };
        this.api.purchasePlanItems(this.query.purId, success);

      },
      inputNumChange(values) {
        this.dataCount = values.total;
        this.totalArray = [this.currency.numFormat(values.total[0]), values.total[1], this.currency.numFormat(values.total[2])];
      },
      emptySelectProduct() {
        if (this.tableParams.dataArray.length > 0) {
          this.tips.ConfirmModal('确认要清空采购商品重新选择吗？', () => {
            this.tableParams.dataArray = [];
            this.totalArray = [0, 0, 0];
            this.editForm.formItemArray.forEach(item => {
              if (item.prop === 'productId') {
                item.value = '';
              }
            });
          });
        }
      },
      empProductSelect() {
        this.editForm.formItemArray.forEach(item => {
          if (item.prop === 'productId') {
            item.options = [];
            item.value = '';
          }
        });
        this.totalArray = [0, 0, 0];
        this.tableParams.dataArray = [];
      },
      handleReset(formName) {
        this.$refs.form.resetForm(formName);
        this.empProductSelect();
      },
      validateSubmitData(productList) {
        if (productList.length < 1) {
          this.tips.MessageModal('warning', '请先选择采购商品！');
          return false;
        }
        let message = '';
        for (let i = 0; i < productList.length; i++) {
          delete productList[i].id;
          if (productList[i].productPrice <= 0) {
            message = '商品【' + productList[i].productName + '】采购价必须大于0';
            break;
          }
          if (productList[i].purNumber < 1) {
            message = '商品【' + productList[i].productName + '】采购数量须大于1';
            break;
          }
        }
        if (message !== '') {
          this.tips.MessageModal('warning', message);
          return false;
        }
        return true;
      },
      coverFormData(valueData) {
        let productList = Object.assign([], this.tableParams.dataArray);
        let result = this.validateSubmitData(productList);
        if (!result) {
          return;
        }
        productList.forEach(item => {
          delete item.id;
        });
        valueData['productList'] = productList;
        valueData['total'] = this.dataCount[1];
        valueData['price'] = this.dataCount[0];
        valueData['elsePrice'] = this.dataCount[2];

        valueData['state'] = 1;
        if (this.query.purId) {
          valueData['updateUser'] = this.userId;
          valueData['id'] = this.query.purId;
          this.edit(valueData);
        } else {
          valueData['userId'] = this.userId;
          this.add(valueData);
        }

      }, add(valueData) {
        let success = data => {
          if (data.code === 'OK') {
            this.tips.MessageModal('success', '新增成功！');
            this.$router.push({
              path: '/purchase-plan',
            });
          } else {
            this.$message.error(data.msg);
          }
        };
        this.api.addPurchasePlan(valueData, success);
      }, edit(valueData) {
        let success = data => {
          if (data.code === 'OK') {
            this.tips.MessageModal('success', '编辑成功');
            this.$router.push({
              path: '/purchase-plan',
              query: {searchCondition: this.query.searchCondition}
            });
          } else {
            this.$message.error(data.msg);
          }
        };
        this.api.updatePurchasePlan(valueData, success);
      },
      handleOperation(rowIndex, row) {
        this.tips.ConfirmModal('确认移除商品【' + row.productName + '】吗？', () => {
          this.tableParams.dataArray.splice(rowIndex, 1);
        });
      },
      analysisProduct() {
        let totalPrice = 0;
        let totalElsePrice = 0;
        let totalNum = 0;
        this.tableParams.dataArray.forEach(el => {
          totalPrice += el.money;
          totalElsePrice += el.elsePrice;
          totalNum += el.purNumber;
        });
        this.dataCount = [totalPrice, totalNum, totalElsePrice]
        totalPrice = this.currency.numFormat(totalPrice);
        totalElsePrice = this.currency.numFormat(totalElsePrice);
        this.totalArray = [totalPrice, totalNum, totalElsePrice];
      },
      selectOnChange(value, item) {
        if (value === '') {
          return;
        }
        if (item.prop === 'supplyId') {
          this.bySupplyGetShop(value);
          this.empProductSelect();
        } else if (item.prop === "productId") {
          let element = {};
          item.options.forEach(em => {
            if (em.item.id === value) {
              element = em.item;
            }
          });
          let row = {
            id: element.id,
            brandCode: element.brandCode,
            productNo: element.supplyProductNo,
            productItemId: element.productId,
            elsePrice: 0,
            memo: '',
            money: 0,
            productPrice: 0,
            productName: element.productName,
            purNumber: 0,
            productWeight: element.productWeight,
            purchasePrice: element.purchasePrice,
            productUnit: element.productUnit,
          };
          this.tableParams.dataArray.push(row);
          let hash = {};
          this.tableParams.dataArray = this.tableParams.dataArray.reduce(function (pre, next) {
            hash[next.productName] ? '' : hash[next.productName] = true && pre.push(next);
            return pre
          }, []);

        }
      },
      callCompany() {
        let param = {
          pageIndex: 1,
          pageSize: 20,
        };
        let success = data => {
          if (data.code === 'OK') {
            this.editForm.formItemArray.forEach(item => {
              if (item.prop === 'companyId') {
                item.options = this.buildExceptKeyAndValue(data.data, "companyName", "id", "label", "value");
              }
            });
          } else {
            this.$message.error(data.msg)
          }
        };
        this.api.addCompanyList(param, success)
      },
      //通过供应商的id显示商品
      bySupplyGetShop(supplyId) {
        let success = data => {
          if (data.code === "OK") {
            this.editForm.formItemArray.forEach(item => {
              if (item.prop === 'productId') {
                item.options = this.buildExceptKeyAndValue(data.data, "productName", "id", "label", "value");
              }
            });
          } else {
            this.$message.error(data.msg)
          }
        };
        this.api.erpPurSupplyProduct({supplyId: supplyId}, success)
      },
      //获取仓库的select列表
      getDepotData() {
        let param = {
          pageIndex: 1,
          pageSize: 20,
        }
        let success = data => {
          if (data.code === 'OK') {
            this.editForm.formItemArray.forEach(item => {
              if (item.prop === 'depotId') {
                item.options = this.buildExceptKeyAndValue(data.data, "depotName", "id", "label", "value");
              }
            });
          } else {
            this.$message.error(data.msg)
          }
        }
        this.api.depotList(param, success)
      },
      //供应商的接口
      getSupplyList() {
        let success = data => {
          if (data.code === 'OK') {
            this.editForm.formItemArray.forEach(item => {
              if (item.prop === 'supplyId') {
                item.options = this.buildExceptKeyAndValue(data.data, "supplyName", "supplyId", "label", "value");
              }
            });
          } else {
            this.$message.error(data.msg)
          }
        }
        this.api.erpPurSupply({}, success)
      }
    }, watch: {
      'tableParams.dataArray': function () {
        this.analysisProduct();
      }
    }
  }
</script>
<style type="less" scoped>
  .tip-purchase {
    font-size: 12px;
    color: lightslategrey;
    line-height: 32px;
    font-weight: bold;
  }
  .tip-purchase-price {
    font-weight: bold;
    color: red;
    font-size: 18px;
  }
</style>
